package com.baike.server;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*
* 服务端接收客户端简单消息
* */
public class UDPServer {
    public static void main(String[] args) {
        socketServer();
    }

    public static void socketServer(){

        DatagramSocket datagramSocket = null;

        try {
            datagramSocket = new DatagramSocket(10000);

            byte[] getDate = new byte[1024];

            DatagramPacket datagramPacket = new DatagramPacket(getDate,getDate.length);

            while (true){

                datagramSocket.receive(datagramPacket);

                int len = datagramPacket.getLength();

                byte[] date = datagramPacket.getData();

                InetAddress inetAddress = datagramPacket.getAddress();

                String receive = new String(date, 0, len, "UTF-8");

                if("close".equals(receive)){
                    System.out.println(inetAddress.getHostAddress()+"用户已经退出会话");
                    break;
                }
                System.out.println(inetAddress.getHostAddress() + ":" + receive);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(datagramSocket != null){
                datagramSocket.close();
            }
        }
    }
}
